﻿using SqliteORM;
using Dimebrain.TweetSharp.Model.Twitter;
using Dimebrain.TweetSharp.Fluent;
using Dimebrain.TweetSharp.Extensions;
using System.Linq;
using System;

namespace TwKarma.Data.Entity
{
	[Table]
	public class TwitterUser : TableBase
	{
		[PrimaryKey]
		public int TwitterId { get; set; }

		[Field(Size = 100)]
		public string ScreenName { get; set; }

		[Field(Size = 300)]
		public string ProfileImageUrl { get; set; }

        [Field]
        public int Score { get; set; }

        [Field]
        public int SumKarmaVotes { get; set; }


        public static int GetId(string screenname)
        {
            using (TableAdapter<TwitterUser> adapter = TableAdapter<TwitterUser>.Open())
            {
                var user = adapter.ReadAll(Where.Equal("ScreenName", screenname)).FirstOrDefault();
                if (user != null)
                    return user.TwitterId;

                var twtuser = TwitterUser.FromScreenName(screenname);
                Store(twtuser);

                return twtuser == null ? 0 : twtuser.Id;                
            }
        }
        
        public static TwitterUser Get(string screenname)
        {
			if (screenname.StartsWith("@"))
				screenname = screenname.Substring(1);

            using (TableAdapter<TwitterUser> adapter = TableAdapter<TwitterUser>.Open())
            {
                TwitterUser userObj = adapter.ReadAll(Where.Like("ScreenName", screenname)).FirstOrDefault();
                if (userObj != null)
                    return userObj;
                
                var twitterUser = TwitterUser.FromScreenName(screenname);
                if (twitterUser == null)
                    return null;

                Store(twitterUser);

				return new TwitterUser() { TwitterId = twitterUser.Id, ScreenName = twitterUser.ScreenName, Score = 0, SumKarmaVotes=0, ProfileImageUrl = twitterUser.ProfileImageUrl };
            }
        }

        public static TwitterUser Get(int userId)
        {
            using (TableAdapter<TwitterUser> adapter = TableAdapter<TwitterUser>.Open())
            {
                TwitterUser userObj = adapter.ReadAll(Where.Equal("TwitterId", userId)).FirstOrDefault();
                if (userObj != null)
                    return userObj;

                var twitterUser = TwitterUser.FromUserId(userId);
				if (twitterUser == null)
					return null;

                Store(twitterUser);

                return new TwitterUser() { TwitterId = twitterUser.Id, ScreenName = twitterUser.ScreenName, Score = 0 };
            }
        }

        private static void Store(Dimebrain.TweetSharp.Model.TwitterUser user)
        {
            if (user == null)
                return;

            using (TableAdapter<TwitterUser> adapter = TableAdapter<TwitterUser>.Open())
                adapter.CreateUpdate(
                    new TwitterUser() 
                    { 
                        TwitterId = user.Id, 
                        ScreenName = user.ScreenName, 
                        Score = 0, 
                        SumKarmaVotes = 0,
                        ProfileImageUrl = user.ProfileImageUrl 
                    });
        }

        protected static Dimebrain.TweetSharp.Model.TwitterUser FromScreenName(string screenname)
        {
            TwitterResult twitterResult = FluentTwitter.CreateRequest().Users().ShowProfileFor(screenname).AsJson().Request();
            if ((twitterResult != null) && !twitterResult.IsTwitterError)
                return twitterResult.AsUser();

            return null;
        }

        protected static Dimebrain.TweetSharp.Model.TwitterUser FromUserId(int userId)
        {
            TwitterResult twitterResult = FluentTwitter.CreateRequest().Users().ShowProfileFor(userId).AsJson().Request();
            if ((twitterResult != null) && !twitterResult.IsTwitterError)
                return twitterResult.AsUser();

            return null;
        }
	}
}
